import request from "@/utils/http";

function markFiles(payload) {
  const copyNewVal = JSON.parse(JSON.stringify(payload));
  const { companyMemberList, registeredOfficeAddressCertificateUrls, registeredOfficeShareholdingStructureUrls, authoritiesApprovalFileUrls } = copyNewVal;
  if (companyMemberList) {
    companyMemberList.forEach((member, idx) => {
      member?.identificationUrls?.forEach((url, index) => {
        url.index = index;
        url.type = "identificationUrls";
        url.belong = "member";
        url.memberIdx = idx;
      });
      member?.addressIdUrls?.forEach((url, index) => {
        url.index = index;
        url.type = "addressIdUrls";
        url.belong = "member";
        url.memberIdx = idx;
      });
      member?.businessLicenseUrls?.forEach((url, index) => {
        url.index = index;
        url.type = "businessLicenseUrls";
        url.belong = "member";
        url.memberIdx = idx;
      });
      member?.ultimateBeneficiaryBusinessLicenseUrls?.forEach((url, index) => {
        url.index = index;
        url.type = "ultimateBeneficiaryBusinessLicenseUrls";
        url.belong = "member";
        url.memberIdx = idx;
      });
    });
  }
  if (registeredOfficeAddressCertificateUrls) {
    registeredOfficeAddressCertificateUrls?.forEach((url, index) => {
      url.index = index;
      url.type = "registeredOfficeAddressCertificateUrls";
    });
  }
  if (registeredOfficeShareholdingStructureUrls) {
    registeredOfficeShareholdingStructureUrls?.forEach((url, index) => {
      url.index = index;
      url.type = "registeredOfficeShareholdingStructureUrls";
    });
  }
  if (authoritiesApprovalFileUrls) {
    authoritiesApprovalFileUrls?.forEach((url, index) => {
      url.index = index;
      url.type = "authoritiesApprovalFileUrls";
    });
  }
  return copyNewVal;
}

export default {
  namespaced: true,
  state: {
    detail: {},
  },
  mutations: {
    SET_DETAIL(state, detail) {
      const markedData = markFiles(detail);
      state.detail = { ...state.detail, ...markedData };
    },
  },
  getters: {
    companyMemberFiles: ({ detail }) => {
      const { companyMemberList } = detail;
      return (
        companyMemberList &&
        companyMemberList.reduce((obj, item) => {
          const km = {
            identificationFiles: "identificationUrls",
            addressFiles: "addressIdUrls",
            businessLicenseFiles: "businessLicenseUrls",
            ultimateBeneficiaryBusinessLicenseFiles: "ultimateBeneficiaryBusinessLicenseUrls",
          };
          Object.keys(km).forEach(k => {
            const m = km[k];
            if (item[m]) {
              if (!obj[k]) {
                obj[k] = [];
              }
              obj[k].push({
                fullName: item.fullName,
                positionHeld: item.positionHeld,
                fileUrls: item[m],
              });
            }
          });
          return obj;
        }, {})
      );
    },
  },
  actions: {
    async initApplyment({ commit }, applymentId) {
      const { data } = await request.get(`/companyApplymentManage/${applymentId}/detail`);
      commit("SET_DETAIL", data);
      return Promise.resolve(data);
    },
    //初审
    doCheck({ commit, state }, applymentStatus) {
      return new Promise((resolve, reject) => {
        request
          .post(`/companyApplymentStatusManage/check`, {
            applymentId: state.detail.id,
            applymentStatus: applymentStatus,
          })
          .then(({ code, msg }) => {
            if (code === 200) {
              const newDetail = { ...this.detail, applymentStatus };
              commit("SET_DETAIL", newDetail);
              resolve();
            } else {
              reject(msg);
            }
          });
      });
    },
    //复核
    doAudit({ commit, state }, applymentStatus) {
      return new Promise((resolve, reject) => {
        request
          .post(`/companyApplymentStatusManage/audit`, {
            applymentId: state.detail.id,
            applymentStatus: applymentStatus,
          })
          .then(({ code, msg }) => {
            if (code === 200) {
              const newDetail = { ...this.detail, applymentStatus };
              commit("SET_DETAIL", newDetail);
              resolve();
            } else {
              reject(msg);
            }
          });
      });
    },
    //驳回
    doReject({ commit, state }) {
      return new Promise((resolve, reject) => {
        const applymentStatus = "REJECTED";
        request
          .post(`/companyApplymentStatusManage/reject`, {
            applymentId: state.detail.id,
            applymentStatus: applymentStatus,
          })
          .then(({ code, msg }) => {
            if (code === 200) {
              const newDetail = { ...this.detail, applymentStatus };
              commit("SET_DETAIL", newDetail);
              resolve();
            } else {
              reject(msg);
            }
          });
      });
    },
    //修改
    doRevise({ commit, state }) {
      return new Promise((resolve, reject) => {
        const applymentStatus = "REVISE_FINISH";
        request.post(`/companyApplymentStatusManage/${state.detail.id}/commitRevision`).then(({ code, msg }) => {
          if (code === 200) {
            const newDetail = { ...this.detail, applymentStatus };
            commit("SET_DETAIL", newDetail);
            resolve();
          } else {
            reject(msg);
          }
        });
      });
    },
    //保存步骤审核
    doSaveProcedures({ commit, state }, payload) {
      return new Promise((resolve, reject) => {
        request.post(`/companyApplymentStatusProcedure/save`, payload).then(({ code, msg }) => {
          if (code === 200) {
            const copy = { ...payload };
            let procedures = [...state.detail.procedures];
            const index = procedures.findIndex(i => i.step === copy.step);
            if (index !== -1) {
              procedures[index] = copy;
            } else {
              procedures = [...procedures, copy];
            }
            commit("SET_DETAIL", { procedures });
            resolve();
          } else {
            reject(msg);
          }
        });
      });
    },
    //保存修改
    doSaveRevising({ commit }, payload) {
      return new Promise((resolve, reject) => {
        const applymentStatus = "REVISING";
        request.post(`/companyApplymentStatusManage/revise`, payload).then(({ code, msg }) => {
          if (code === 200) {
            const newDetail = JSON.parse(JSON.stringify(payload));
            newDetail.applymentStatus = applymentStatus;
            commit("SET_DETAIL", newDetail);
            resolve();
          } else {
            reject(msg);
          }
        });
      });
    },
    //更新文件
    doUpdateFiles({ state, commit }, file) {
      return new Promise((resolve, reject) => {
        const newDetail = JSON.parse(JSON.stringify(state.detail));
        if (file.belong && file.belong === "member") {
          newDetail.companyMemberList[file.memberIdx][file.type][file.index] = file;
        } else {
          newDetail[file.type][file.index] = file;
        }
        request.post(`/companyApplymentStatusManage/revise`, newDetail).then(({ code, msg }) => {
          if (code === 200) {
            commit("SET_DETAIL", newDetail);
            resolve();
          } else {
            reject(msg);
          }
        });
      });
    },
    //认领
    doClaimOwnership({ state, commit }, { ownershipRole, toUser }) {
      return new Promise((resolve, reject) => {
        const newDetail = JSON.parse(JSON.stringify(state.detail));
        newDetail[ownershipRole] = toUser;
        request
          .post(`/companyApplymentStatusManage/claimOwnership`, {
            applymentId: newDetail.id,
            ownershipRole: ownershipRole,
          })
          .then(({ code, msg }) => {
            if (code === 200) {
              commit("SET_DETAIL", newDetail);
              resolve();
            } else {
              reject(msg);
            }
          });
      });
    },
    //转让
    doTransferOwnership({ state, commit }, { ownershipRole, toUser }) {
      return new Promise((resolve, reject) => {
        const newDetail = JSON.parse(JSON.stringify(state.detail));
        newDetail[ownershipRole] = toUser;
        request
          .post(`/companyApplymentStatusManage/transferOwnership`, {
            applymentId: newDetail.id,
            ownershipRole: ownershipRole,
            to: toUser.id,
          })
          .then(({ code, msg }) => {
            if (code === 200) {
              commit("SET_DETAIL", newDetail);
              resolve();
            } else {
              reject(msg);
            }
          });
      });
    },
    //调整
    doAdjustOwnership({ state, commit }, { ownershipRole, toUser }) {
      return new Promise((resolve, reject) => {
        const newDetail = JSON.parse(JSON.stringify(state.detail));
        newDetail[ownershipRole] = toUser;
        request
          .post(`/companyApplymentStatusManage/adjustOwnership`, {
            applymentId: newDetail.id,
            ownershipRole: ownershipRole,
            to: toUser.id,
          })
          .then(({ code, msg }) => {
            if (code === 200) {
              commit("SET_DETAIL", newDetail);
              resolve();
            } else {
              reject(msg);
            }
          });
      });
    },
  },
};
